package com.css.fxfzdzzh.modules.downloadLegend.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzdzzh.base.attachment.repository.AttachmentInfoRepository;
import com.css.fxfzdzzh.base.dict.repository.DictItemRepository;
import com.css.fxfzdzzh.base.dict.repository.entity.DictItemEntity;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.constants.YNEnum;
import com.css.fxfzdzzh.modules.downloadLegend.Vo.LegendVo;
import com.css.fxfzdzzh.modules.downloadLegend.Vo.RequestVO;
import com.css.fxfzdzzh.modules.downloadLegend.Vo.ResponseVO;
import com.css.fxfzdzzh.modules.downloadLegend.entity.*;
import com.css.fxfzdzzh.modules.downloadLegend.service.DownloadsFile;
import com.css.fxfzdzzh.modules.downloadLegend.service.SupergraphService;
import com.css.fxfzdzzh.modules.hypergraph.service.HypergraphService;
import com.css.fxfzdzzh.modules.mapManagement.entity.MapTemplate;
import com.css.fxfzdzzh.modules.mapManagement.service.MapService;
import com.css.fxfzdzzh.modules.mapManagement.service.MapTemplateService;
import com.css.fxfzdzzh.modules.mapManagement.vo.MapVO;
import com.css.fxfzdzzh.modules.taskManage.entity.TaskEntity;
import com.css.fxfzdzzh.modules.taskManage.repository.TaskRepository;
import com.css.fxfzdzzh.util.*;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import com.css.fxfzdzzh.zcpt.sys.entity.SUser;
import com.css.fxfzdzzh.zcpt.sys.service.SUserService;
import lombok.extern.slf4j.Slf4j;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;


@Service
@Slf4j
public class SupergraphServiceImpl implements SupergraphService {
    @Resource
    RestTemplateUtil restTemplateUtil;

    @Value("${file.localDir}")
    private String ctLocalDir;

    @Resource
    private DownloadsFile downloadsFile;
    @Resource
    private AttachmentInfoRepository attachmentInfoRepository;
    @Resource
    private SUserService sUserService;
    @Resource
    private MapService mapService;
    @Resource
    private TaskRepository taskRepository;
    @Resource
    private DictItemRepository dictItemRepository;
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    private HypergraphService hypergraphService;
    @Resource
    RestTemplate restTemplate;
    @Resource
    MapTemplateService mapTemplateService;

    //超图web打印功能
    public RestResponse supergraph(RequestVO requestVO, String iServerHttpUrl, String token) throws Exception {
        RestResponse restResponse = null;
        String url = iServerHttpUrl + "/webprinting/rest/webprinting/v1/jobs.json?token=" + token;
        JSONObject requestJsonVo = (JSONObject) JSONObject.toJSON(requestVO);
        String json = JSONObject.toJSONString(requestJsonVo);
        log.info(json);
        Map map = JSONObject.parseObject(json, Map.class);
        ResponseEntity<String> stringResponseEntity = restTemplateUtil.sendPostHttpRequest(url, map);
        String body = stringResponseEntity.getBody();
        List<ResponseVO> responseVO = JSON.parseArray(body, ResponseVO.class);
        String path = "";
        if (responseVO != null || responseVO.size() > 0) {
            path = responseVO.get(0).getPath() + "/" + "result";
            String savePath = ctLocalDir;
            path = path.replace("@", "%40");
            System.out.println("路径  " + path);
            System.out.println("paramMap:" + map);
            String path2 = responseVO.get(0).getPath() + ".rjson";
            Map<String, Object> map2 = new HashMap<>();
            boolean flag = true;
            while (flag) {
                ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(path2, map2);
                String body1 = responseEntity.getBody();
                String[] split1 = body1.split("status");
                if (split1[1].contains("ERROR")) {
                    log.error("超图服务打印失败");
                    return RestResponse.fail("超图服务打印失败");
                }
                if (split1[1].contains("FINISHED")) {
                    flag = false;
                    continue;
                }
//                Thread.sleep(500);
            }
            //下载文件并获取文件ID
            restResponse = downloadsFile.downloadByUrl(path, savePath);
        }
        File file = new File(ctLocalDir);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isFile()) {
                file1.delete();
            }
        }

        return restResponse;
    }

    @Override
    public RestResponse handle(LegendVo legendVo) {
        RestResponse restResponse = null;
        try {
            //任务id;
            String id = legendVo.getDtId();
            //区域空间数据
            String geomText = legendVo.getGeomText();
            String extent = "";
            String center = "";
            if (PlatformObjectUtils.isNotEmpty(id)) {//根据任务ID查询图件范围和中心点
                //获取任务范围矩形区域
                extent = taskRepository.getExtent(id);
                //获取任务范围中心点
                center = taskRepository.getCenter(id);
            } else if (PlatformObjectUtils.isNotEmpty(geomText)) {//根据区域空间数据查询图件范围和中心点
                extent = getExtent(geomText);
                center = getCenter(geomText);
            }
            if (PlatformObjectUtils.isNotEmpty(extent) && PlatformObjectUtils.isNotEmpty(center)) {
                String[] split = extent.substring(4, extent.length() - 1).split(",");
                String[] s1 = split[0].split(" ");
                String[] s2 = split[1].split(" ");
                String leftX = s1[0];
                String leftY = s1[1];
                String rightX = s2[0];
                String rightY = s2[1];
//                int level = getLevel(Double.valueOf(leftX), Double.valueOf(leftY), Double.valueOf(rightX), Double.valueOf(rightY));
                int level = getLevel(Double.valueOf(leftX), Double.valueOf(leftY), Double.valueOf(rightX), Double.valueOf(rightY), null);
                String[] s = center.substring(6, center.length() - 1).split(" ");
                String centerX = s[0];
                String centerY = s[1];
                Map<String, Double> hashMap = new HashMap<>();
                hashMap.put("leftX", Double.valueOf(leftX));
                hashMap.put("leftY", Double.valueOf(leftY));
                hashMap.put("rightX", Double.valueOf(rightX));
                hashMap.put("rightY", Double.valueOf(rightY));
                hashMap.put("centerX", Double.valueOf(centerX));
                hashMap.put("centerY", Double.valueOf(centerY));
                hashMap.put("level", Double.valueOf(level));
                //获取Web打印出图模板列表
                List<TemplateEntity> templateEntityList = hypergraphService.getWebprintingLayoutsList();
                legendVo.setTemplateEntityList(templateEntityList);
                //生成图件
                restResponse = toData(legendVo, hashMap);
            }
        } catch (Exception e) {
            String errorMessage = "生成图件失败!";
            log.error(errorMessage, e);
            restResponse = RestResponse.fail(errorMessage);
        }
        return restResponse;
    }

    //获取范围矩形区域
    public String getExtent(String geomText) {
        String sql = "select ST_extent(st_geomfromtext('" + geomText + "',4490))";
        return jdbcTemplate.queryForObject(sql, String.class);
    }

    //获取范围中心点
    public String getCenter(String geomText) {
        String sql = "select ST_AsText(ST_Centroid(ST_extent(st_geomfromtext('" + geomText + "',4490))))";
        return jdbcTemplate.queryForObject(sql, String.class);
    }

    /*//根据经纬度范围获取level值
    public int getLevel(double leftBottom_X,double leftBottom_Y,double rightTop_X,double rightTop_Y) {
        int level = 4;//默认级别4
        double minLon = leftBottom_X;
        double minLat = leftBottom_Y;
        double maxLon = rightTop_X;
        double maxLat = rightTop_Y;
        //获取最大差值
        double diffLon = maxLon - minLon;
        double diffLat = maxLat - minLat;
        double diffMax = diffLon;
        if(diffLon < diffLat){
            diffMax = diffLat;
        }
//        int diff = Math.round(diffMax);
//        long round = Math.round(diffMax);
        int[] levelArr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
        Double[] diffArr = {360.0,180.0,90.0,45.0,22.0,11.0,5.0,2.5,1.25, 0.6,0.3,0.15,0.07,0.03,0.0};
        for (int i = 0; i < diffArr.length; i++) {
            if (diffMax - diffArr[i] >= 0) {
                level = levelArr[i];
                break;
            }
        }

        return level;
    }*/

    //根据经纬度范围获取level值
    public int getLevel(double leftBottom_X, double leftBottom_Y, double rightTop_X, double rightTop_Y, TemplateEntity templateEntity) {
        int level = 4;//默认级别4
        double minLon = leftBottom_X;
        double minLat = leftBottom_Y;
        double maxLon = rightTop_X;
        double maxLat = rightTop_Y;
        //获取最大差值
        double diffLon = maxLon - minLon;
        double diffLat = maxLat - minLat;
        double diffMax = diffLon;
        if (diffLon < diffLat) {
            diffMax = diffLat;
        }
//        int diff = Math.round(diffMax);
//        long round = Math.round(diffMax);
        //1-18缩放级别zoom
        /*int[] levelArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18};
        Double[] diffArr = {360.0,180.0,90.0,45.0,22.0,11.0,5.0,2.5,1.25, 0.6,0.3,0.15,0.07,0.03,0.015,0.007,0.0003,0.00015};
        for (int i = 0; i < diffArr.length; i++) {
            if (diffMax - diffArr[i] >= 0) {
                level = levelArr[i];
                break;
            }
        }*/
        int width = 1510;
        int height = 1020;
        //根据超图模板信息
        if (templateEntity != null) {
            width = templateEntity.getWebMapFrameSizeX();//图件宽度
            height = templateEntity.getWebMapFrameSizeY();//图件高度
        }
        //根据区域范围计算zoom级别，width、height是以像素为单位的地图布局大小
        level = getBoundsZoomLevel(leftBottom_X, leftBottom_Y, rightTop_X, rightTop_Y, width, height);
        //至少为4级，防止地图经纬度格网不显示
        if(level<4){
            level = 4;
        }

        return level;
    }

    final static int GLOBE_WIDTH = 256;
    final static int ZOOM_MAX = 18;

    //根据区域范围计算zoom级别，width、height是以像素为单位的地图布局大小
    public static int getBoundsZoomLevel(double leftBottom_X, double leftBottom_Y, double rightTop_X, double rightTop_Y,
                                         int width, int height) {
        double latFraction = (latRad(rightTop_Y) - latRad(leftBottom_Y)) / Math.PI;
        double lngDiff = rightTop_X - leftBottom_X;
        double lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
        double latZoom = zoom(height, GLOBE_WIDTH, latFraction);
        double lngZoom = zoom(width, GLOBE_WIDTH, lngFraction);
        double zoom = Math.min(Math.min(latZoom, lngZoom), ZOOM_MAX);
        return (int) (zoom);
    }

    private static double latRad(double lat) {
        double sin = Math.sin(lat * Math.PI / 180);
        double radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
        return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
    }

    private static double zoom(double mapPx, double worldPx, double fraction) {
        final double LN2 = .693147180559945309417;
        return (Math.log(mapPx / worldPx / fraction) / LN2);
    }

    //获取经纬网参数
    public MapGridOptions getMapGridOptions(double leftBottom_X, double leftBottom_Y, double rightTop_X, double rightTop_Y) {
        double minLon = leftBottom_X;
        double minLat = leftBottom_Y;
        double maxLon = rightTop_X;
        double maxLat = rightTop_Y;
        //获取经度差值
        double diffLon = maxLon - minLon;
        double tempLon = diffLon / 4;
        if (tempLon > 1) {
            tempLon = Math.round(tempLon);
        } else if (tempLon > 0.5) {
            tempLon = 0.5;//30分
        } else if (tempLon > 0.25) {
            tempLon = 0.25;//15分
        } else if (tempLon > 0.125) {
            tempLon = 0.125;//7分30秒
        } else if (tempLon > 0.0625) {
            tempLon = 0.0625;//3分45秒
        } else if (tempLon > 0.05) {
            tempLon = 0.05;//3分
        } else if (tempLon > 0.025) {
            tempLon = 0.025;//1分30秒
        } else if (tempLon > 0.0125) {
            tempLon = 0.0125;//45秒
        } else {
            tempLon = 0.0025;//9秒
        }
        //获取纬度差值
        double diffLat = maxLat - minLat;
        double tempLat = diffLat / 3;
        if (tempLat > 1) {
            tempLat = Math.round(tempLat);
        } else if (tempLat > 0.5) {
            tempLat = 0.5;//30分
        } else if (tempLat > 0.25) {
            tempLat = 0.25;//15分
        } else if (tempLat > 0.125) {
            tempLat = 0.125;//7分30秒
        } else if (tempLat > 0.0625) {
            tempLat = 0.0625;//3分45秒
        } else if (tempLat > 0.05) {
            tempLat = 0.05;//3分
        } else if (tempLat > 0.025) {
            tempLat = 0.025;//1分30秒
        } else if (tempLat > 0.0125) {
            tempLat = 0.0125;//45秒
        } else {
            tempLat = 0.0025;//9秒
        }
        MapGridOptions mapGridOptions = new MapGridOptions();//经纬度网格边框
        mapGridOptions.setOriginX(-180);
        mapGridOptions.setOriginY(-90);
        mapGridOptions.setCellWidth(tempLon);
        mapGridOptions.setCellHeight(tempLat);
        mapGridOptions.setMarkType("DMS");

        return mapGridOptions;
    }

    //根据level获取经纬网参数
    public MapGridOptions getMapGridOptionsByLevel(double level) {
        int[] levelArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18};
        double[] cellDiffArr = {160, 80, 40, 20, 10, 5, 2.5, 1.25, 0.5, 0.25, 0.125, 0.0625, 0.05, 0.025, 0.0125, 0.005, 0.0025, 0.0011};
        double cellDiff = 1;
        for (int i = 0; i < levelArr.length; i++) {
            if (levelArr[i] == level) {
                cellDiff = cellDiffArr[i];
                break;
            }
        }
        MapGridOptions mapGridOptions = new MapGridOptions();//经纬度网格边框
        mapGridOptions.setOriginX(-180);
        mapGridOptions.setOriginY(-90);
        mapGridOptions.setCellWidth(cellDiff);
        mapGridOptions.setCellHeight(cellDiff);
        mapGridOptions.setMarkType("DMS");

        return mapGridOptions;
    }

    //用URLEncode编码，防止如%符号不能打印
    public String setStringEncoder(String string) {
        String stringEncoder = string;
        try {
            stringEncoder = URLEncoder.encode(string, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return stringEncoder;
    }

    //生成图件
    private RestResponse toData(LegendVo legendVo, Map<String, Double> hashMap) throws Exception {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String iServerHttpUrl = configGroup.getProperty("supergraphRestTemplateUrl");//超图服务路径
        //设置打印内容请求体
        RequestVO requestVO = getRequestVO(iServerHttpUrl, legendVo, hashMap);
        //获取超图服务token
        String token = hypergraphService.getToken();
        if (PlatformObjectUtils.isEmpty(token)) {
            return RestResponse.fail("缺少超图服务token");
        }
        //超图web打印功能
        RestResponse response = supergraph(requestVO, iServerHttpUrl, token);
        if (response.getCode() != 200) {
            return response;
        }
        String attachId = response.getData().toString();//图件文件id
        //图件信息
        MapVO mapVO = legendVo.getMapVO();
        mapVO.setAttachmentId(attachId);
        mapVO.setUnit(legendVo.getUnit());
        if (PlatformObjectUtils.isNotEmpty(legendVo.getDtId())) {
            mapVO.setNum(legendVo.getDtId());
        }
        //新增图件
        mapService.uploadMap(mapVO);

        return RestResponse.succeed("保存成功");
    }

    //根据超图模板名、模板信息列表获取模板信息
    public TemplateEntity getTemplateEntityByTemplateName(String smTemplateName, List<TemplateEntity> templateEntityList) {
        TemplateEntity templateEntity = null;
        if (PlatformObjectUtils.isNotEmpty(smTemplateName) && templateEntityList.size() > 0) {
            for (TemplateEntity entity : templateEntityList) {
                if (smTemplateName.equals(entity.getTemplateName())) {
                    templateEntity = entity;
                    break;
                }
            }
        }

        return templateEntity;
    }

    //设置打印内容请求体
    private RequestVO getRequestVO(String iServerHttpUrl, LegendVo legendVo, Map<String, Double> hashMap) throws InterruptedException {
        String templateName = null;
        String mapTemplateAttachId = legendVo.getMapTemplateAttachId();//图件模板附件id
//        AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(mapTemplateAttachId);
        MapTemplate mapTemplate = mapTemplateService.getByAttachId(mapTemplateAttachId);//用附件ID查找图件模板信息
        if (mapTemplate != null) {
            //获取Web打印出图模板列表
            List<TemplateEntity> templateEntityList = legendVo.getTemplateEntityList();
            //根据超图模板名、模板信息列表获取模板信息
            TemplateEntity templateEntity = getTemplateEntityByTemplateName(mapTemplate.getSmTemplateName(), templateEntityList);
            if (templateEntity != null) {
                templateName = templateEntity.getTemplateName();
            }
        }
        if (PlatformObjectUtils.isEmpty(templateName)) {//如果没有模板名，则使用默认模板
            templateName = "Administrative_Active_Fault-hf1012";
        }
        RequestVO requestVO = new RequestVO();
        //layoutOptions
        LayoutOptions layoutOptions = new LayoutOptions();
        layoutOptions.setTemplateName(templateName);//模板名
//        layoutOptions.setTemplateName("Administrative_Active_Fault-hf");//test
        //查询字典项--图件分类二级标题
        DictItemEntity dictItemEntity = dictItemRepository.findOneByDictItemIdAndDictId(legendVo.getMapVO().getMapLevel1Category(), legendVo.getMapVO().getMapLevel2Category());
        String dictItemName = dictItemEntity.getDictItemName();
        layoutOptions.setTitle(dictItemName);//图件标题
        if (dictItemName.equals("XX度地震滑坡风险分布图")) {
            layoutOptions.setTitle(legendVo.getTitle());//图件标题
        } else if (dictItemName.equals("黄土高原50年超越概率XX%地震滑坡危险等级评价图")) {
            //用URLEncode编码，防止如%符号不能打印
            String title = setStringEncoder(legendVo.getTitle());
            layoutOptions.setTitle(title);//图件标题
        }
        layoutOptions.setAuthor("制图单位：" + legendVo.getUnit());//制图单位
        String date = DateUtil.format(new Date(), "yyyy年MM月dd日");
        layoutOptions.setTime("制图时间:" + date);//制图时间
        // layoutOptions.setSummaryText(legendVo.getMapVO().getMapDesc());
        //比例尺
        ScaleBarOptions scaleBarOptions = new ScaleBarOptions("", "BAR", 5, "METER");
        layoutOptions.setScaleBarOptions(scaleBarOptions);
        //指北针
//        NorthArrowOptions northArrowOptions = new NorthArrowOptions("file://NorthArrow.svg");
        NorthArrowOptions northArrowOptions = new NorthArrowOptions("file://ARROW_RIGHT_FILL_WITH_COLOR.svg");
        layoutOptions.setNorthArrowOptions(northArrowOptions);
        //获取经纬网参数
//        MapGridOptions mapGridOptions = getMapGridOptions(hashMap.get("leftX"), hashMap.get("leftY"), hashMap.get("rightX"), hashMap.get("rightY"));
        //根据level获取经纬网参数
        MapGridOptions mapGridOptions = getMapGridOptionsByLevel(hashMap.get("level"));
        layoutOptions.setMapGridOptions(mapGridOptions);
        //图例
        LegendOption legendOption = new LegendOption();
        legendOption.setTitle("图 例");//图例名
        legendOption.setIsAutoComposition(true);//是否自动排版
        //获取显示图例的地图url列表
        List<Layerr> layerrs = new ArrayList<>();
        List<Layerr> legendSetList = legendVo.getLegendSetList();//图层（临时图层）url列表--用于显示图例
        for (Layerr layerr : legendSetList) {
            //获取图层图例（除文字标签）
            layerr = getLayerrByLayerNameUrl(layerr.getUrl());
            layerrs.add(layerr);
        }
        legendOption.setLayers(layerrs);
        layoutOptions.setLegendOptions(legendOption);
        requestVO.setLayoutOptions(layoutOptions);
        //exportOptions
        ExportOptions exportOptions = new ExportOptions("png", 120.0);//dpi取值推荐：72,120,200,254,300
        requestVO.setExportOptions(exportOptions);
        //content
        Content content = new Content();
        content.setType("WEBMAP");
        com.css.fxfzdzzh.modules.downloadLegend.entity.Value value = new com.css.fxfzdzzh.modules.downloadLegend.entity.Value();
        leftAndright leftBottom = new leftAndright(hashMap.get("leftX"), hashMap.get("leftY"));
        leftAndright rightTop = new leftAndright(hashMap.get("rightX"), hashMap.get("rightY"));
        Extent extent = new Extent(leftBottom, rightTop);
        value.setExtent(extent);
        value.setMaxScale("1:2130.3378410848");
        value.setLevel(hashMap.get("level"));
//        value.setLevel(11.0);
        leftAndright center = new leftAndright(hashMap.get("centerX"), hashMap.get("centerY"));
        value.setCenter(center);
        //底图
//        BaseLayer baseLayer = new BaseLayer("TILE", "China", "http://10.13.155.192:8090/iserver/services/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg");
//        value.setBaseLayer(baseLayer);
        //获取显示图层的地图url列表
        List<Layer> layers = getLayers(iServerHttpUrl, legendVo.getMapVO().getMapLevel2Category(), legendVo.getTempLayersSetList());//图件分类二级
        value.setLayers(layers);
        value.setDescription("");
        value.setProjection("EPSG:4490");
        value.setMinScale("1:591658710.909131");
        value.setTitle("China");
        value.setVersion("2.3.0");
        content.setValue(value);
        requestVO.setContent(content);
        return requestVO;
    }

    private List<Layer> getLayers(String iServerHttpUrl, String dictCode, List<TempLayersSet> tempLayersSetList) throws InterruptedException {
        String url = iServerHttpUrl;
        List<Layer> layers = new ArrayList<>();
        if (tempLayersSetList != null && tempLayersSetList.size() > 0) {
            for (int i = 0; i < tempLayersSetList.size(); i++) {
                TempLayersSet tempLayersSet = tempLayersSetList.get(i);
                String name = tempLayersSet.getName();
                String tempLayerUrl = tempLayersSet.getUrl();
                //获取临时图层
                tempLayerUrl = getSqlTempLayer(tempLayerUrl, null, true);
                Layer layer = new Layer("TILE", name, tempLayerUrl);
                layers.add(layer);
            }
        }
        /*//地震烈度与地震地质灾害分布图
        if ("24".equals(dictCode)) {
            String url1 = url + "/map-fxfzdzzh/rest/maps/dzzh_slide_result_intensity@fxfzdzzh";
            Layer layer1 = new Layer("TILE",true,"dzzh_slide_result_intensity",url1);
            layers.add(layer1);
        }*/
        return layers;
    }

    //获取图层图例（除文字标签）
    public Layerr getLayerrByLayerNameUrl(String layerUrl) {
        //获取图层图例名称数组（除文字标签）
        List<String> strings = getLegendLayerNameList(layerUrl);
        Layerr layerr = new Layerr(layerUrl, strings);

        return layerr;
    }

    //获取图层图例名称数组（除文字标签）
    private List<String> getLegendLayerNameList(String layerUrl) {
        //如果没有文字标签，则返回空数组代表显示全部图例
        List<String> legendLayerNameList = new ArrayList<>();
        JSONArray jsonArray = getLayersRJson(layerUrl);
        boolean bool = false;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONArray layers = jsonArray.getJSONObject(i).getJSONObject("subLayers").getJSONArray("layers");
            for (int j = 0; j < layers.size(); j++) {
                JSONObject layer = layers.getJSONObject(j);
                JSONObject datasetInfo = layer.getJSONObject("datasetInfo");
                String layerName = datasetInfo.getString("name") + "@" + datasetInfo.getString("dataSourceName");
                //获取图层过滤条件
                String name = layer.getString("name");
                name = name.replace("#", ".");
                String legendLayerName = name + "@@" + layerName;
                String ugcLayerType = layer.getString("ugcLayerType");
                if (ugcLayerType.equals("THEME")) {
                    if ("LABEL".equals(layer.getJSONObject("theme").getString("type"))) {
                        //文字标签
                        bool = true;
                    } else {
                        legendLayerNameList.add(legendLayerName);
                    }
                } else {
                    legendLayerNameList.add(legendLayerName);
                }
            }
        }
        if (bool == false) {//无文字标签显示全部图例
            legendLayerNameList = new ArrayList<>();
        }

        return legendLayerNameList;
    }

    //获取临时图层url
    private String getSqlTempLayer(String layerUrl, String sqlText, boolean showLabelBool) throws InterruptedException {
        String resultUrl = layerUrl;
        boolean bool = true;//是否为整图层，不用获取临时图层
        boolean captionBool = false;//是否要修改图例名称
        if (PlatformObjectUtils.isNotEmpty(sqlText)) {
            bool = false;
        }
        JSONArray jsonArray = getLayersRJson(layerUrl);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONArray layers = jsonArray.getJSONObject(i).getJSONObject("subLayers").getJSONArray("layers");
            for (int j = 0; j < layers.size(); j++) {
                JSONObject layer = layers.getJSONObject(j);
                //获取图层过滤条件
                String displayFilter = layer.getString("displayFilter");
                if (PlatformObjectUtils.isNotEmpty(sqlText)) {
                    if (PlatformObjectUtils.isNotEmpty(displayFilter)) {
                        displayFilter = "(" + displayFilter + ") AND " + sqlText;
                    } else {
                        displayFilter = sqlText;
                    }
                }
                layer.put("displayFilter", displayFilter);
                if (showLabelBool == false && layer.getString("ugcLayerType") == "THEME") {
                    if (layer.getJSONObject("theme").getString("type") == "LABEL") {//文字标签子图层
                        layer.put("visible", showLabelBool);
                    }
                }
                //修改图例图层名称
                String caption = layer.getString("caption");
                if(caption.startsWith("final_综合地形指数")){//砂土液化层次分析法综合地形指数
                    layer.put("caption","综合地形指数评估结果");
                    captionBool = true;
                }else if(caption.startsWith("final_场地类别_活动构造区")){//砂土液化层次分析法场地类别活动构造区
                    layer.put("caption","活动构造区评估结果");
                    captionBool = true;
                }else if(caption.startsWith("final_场地类别_稳定大陆区")){//砂土液化层次分析法场地类别稳定大陆区
                    layer.put("caption","稳定大陆区评估结果");
                    captionBool = true;
                }else if(caption.startsWith("final_重分类_自然分割")){//砂土液化层次分析法评估结果
                    layer.put("caption","层次分析法评估结果");
                    captionBool = true;
                }
            }
        }
        String jsonStr = JSON.toJSONString(jsonArray);
        if(bool){//整图层
            if(captionBool){
                //修改图层图例显示名称
                resultUrl = putLayerCaption(layerUrl, jsonStr);
                Thread.sleep(2000);//等待修改图层图例显示名称成功
            }
        }else{//获取临时图层
            JSONObject resultObj = postTempLayersSet(layerUrl, jsonStr);
            String newResourceID = resultObj.getString("newResourceID");
            String newResourceLocation = resultObj.getString("newResourceLocation");
            if (PlatformObjectUtils.isNotEmpty(newResourceLocation)) {
                resultUrl = newResourceLocation.replace(".rjson", "");
            }
        }
        return resultUrl;
    }

    private JSONArray getLayersRJson(String layerUrl) {
        try {
            String dataUrl = layerUrl + "/layers.rjson";
            if (layerUrl.indexOf("tempLayersSet") != -1) {
                dataUrl = layerUrl + ".rjson";//临时图层
            }
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return null;
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, String.class);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(exchange));
            JSONArray body = JSON.parseArray(jsonObject.getString("body"));
            if (body == null) {
                return null;
            }
            return body;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private JSONObject postTempLayersSet(String layerUrl, String jsonStr) {
        JSONObject result = new JSONObject();
        String dataUrl = layerUrl + "/tempLayersSet.rjson";
        try {
            dataUrl = URLDecoder.decode(dataUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=UTF-8");

        HttpEntity<String> entity = new HttpEntity<>(jsonStr, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(exchange));
        JSONObject body = JSON.parseObject(jsonObject.getString("body"));
        if (body == null) {
            return null;
        }
        result = body;

        return result;
    }

    //修改图层图例显示名称
    private String putLayerCaption(String layerUrl, String jsonStr) {
        String dataUrl = layerUrl + "/layers.rjson";
        try {
            dataUrl = URLDecoder.decode(dataUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=UTF-8");

        HttpEntity<String> entity = new HttpEntity<>(jsonStr, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.PUT, entity, String.class);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(exchange));
        JSONObject body = JSON.parseObject(jsonObject.getString("body"));
        if (body == null) {
            return null;
        }

        return layerUrl;
    }

    //根据dictCode、任务ID获取临时图层URL的Map
    public Map<String, String> getTempLayerUrlMapByDictCode(String dictCode, String taskId) throws InterruptedException {
        Map<String, String> tempLayerUrlMap = new HashMap<>();
        //设置地震点分布图
        if ("Scenario_Earthquake".equals(dictCode)) {
            String tempLayerUrl = getTempLayerUrlByDataType("setting_seismic_point", taskId);
            tempLayerUrlMap.put("setting_seismic_point", tempLayerUrl);
        }
        return tempLayerUrlMap;
    }

    //根据数据类型、任务ID获取临时图层URL
    public String getTempLayerUrlByDataType(String dataType, String taskId) throws InterruptedException {
        String tempLayerUrl = "";
        String layerUrl = "";
        String sqlText = "";
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        if (dataType.equals("setting_seismic_point")) {
            layerUrl = url + "/map-fxfzypg/rest/maps/setting_seismic_point@fxfzypg";
            sqlText = "task_id='" + taskId + "' and is_delete='0'";
        }
        if (PlatformObjectUtils.isNotEmpty(layerUrl)) {
            //获取临时图层
            tempLayerUrl = getSqlTempLayer(layerUrl, sqlText, true);
        }
        return tempLayerUrl;
    }


}
